package com.masu.knows.portal.service.impl;

import com.masu.knows.portal.mapper.UserMapper;
import com.masu.knows.portal.model.Permission;
import com.masu.knows.portal.model.Role;
import com.masu.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author 沈传尚
 * @date 2021/12/11
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据用户名查询用户对象
        User user = userMapper.findUserByUsername(username);
        // 2.判断用户是否存在
        if (user==null){
            return null;
        }
        // 3.查询当前用户的所有权限
        List<Permission> ps = userMapper.getPermissionsByUserId(user.getId());
        // 4.转换权限list为String
        String[] auth=new String[ps.size()];
        int i=0;
        for (Permission p : ps){
            auth[i]=p.getName();
            i++;
        }
        // 根据用户id获取用户的所有权限
        List<Role> roles = userMapper.findAllRolesById(user.getId());
        // 数组扩容
        auth=Arrays.copyOf(auth, auth.length + roles.size());
        for (Role r : roles){
            auth[i++]=r.getName();
        }
        // 5.构建UserDetails对象用于返回
        UserDetails u = org.springframework.security.core.userdetails.User.builder()
                .password(user.getPassword())
                .username(user.getUsername())
                .authorities(auth)
                // 设置账号是否被锁定 0-》否，1-》是 ;  "user.getLocked()==1"为true表示锁定 false表示不锁定
                .accountLocked(user.getLocked() == 1)
                // 设置账户是否被禁用  0-》否，1-》是; true表示禁用 false表示不禁用.
                .disabled(user.getEnabled() == 0).build();
        // 6.返回user对象
        return u;
    }
}
